package com.mathdroid.gui.main.filter;

import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import com.mathdroid.model.EModelObserverEvent;
import com.mathdroid.model.IModelObserver;
import com.mathdroid.model.Model;
import com.mathdroid.model.items.SourceCondition;

/**
 * This panel gives the option to edit item browser filters.
 */
public final class FilterPanel extends JPanel implements IModelObserver {
	/**
	 * Default UID.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * The checkboxes for source filters.
	 */
	private final JList sources = new JList();
	
	/**
	 * Create a filter panel.
	 */
	public FilterPanel() {
		Model.registerObserver(this);
		
		this.setLayout(new GridLayout(1, 1));
		
		this.refresh();
		
		this.sources.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.sources.setCellRenderer(new FilterCellRenderer());
		this.sources.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(final MouseEvent e) {
				final int index = sources.locationToIndex(e.getPoint());
				FilterElement item = (FilterElement) sources.getModel()
						.getElementAt(index);
				final boolean enabled = !item.isEnabled();
				item.setEnabled(enabled);
				Rectangle rect = sources.getCellBounds(index, index);
				sources.repaint(rect);
				Model.getProfile().getItemBrowserModel().getSourceConditions()
					.get(index).setEnabled(enabled);
				Model.refreshItemBrowserModel();
			}
		});
		
		final JScrollPane sp = new JScrollPane(this.sources);
		
		this.add(sp);
	}
	
	/**
	 * Refresh the check boxes, so that they match the model.
	 */
	public void refresh() {
		DefaultListModel model = new DefaultListModel();
		this.sources.setModel(model);
		
		for (SourceCondition sc : Model.getProfile().getItemBrowserModel()
				.getSourceConditions()) {
			model.addElement(new FilterElement(
					sc.getSource(), sc.isEnabled(), sc.getIcon()));
		}
	}

	@Override
	public void modelChanged(final EModelObserverEvent e) {
		if (e == EModelObserverEvent.PROFILE_LOADED) {
			this.refresh();
		}
	}
}
